const Sequelize = require("sequelize")
const {
  Goods,
  GoodsAttr,
  GoodsAttrValue,
  GoodsAttrResult,
  GoodsAttrConfig,
  StoreHouse,
  Order,
  OrderGoods,
  Customer
} = require("../model")
const moment = require("moment")

// const { CustomerController, GoodsController } = require("./index")
const CustomerController = require("./customer_controller")
const GoodsController = require("./goods_controller")

const OrdersHasManyGoods = Order.hasMany(OrderGoods, {
  foreignKey: "order_id",
  constraints: false,
  as: "goods_list",
  order: ["sort", "ASC"]
})
const utils = require("../utils/index.js")
const { sqlConn } = require("../db/connect")

// 新增订单
const createOrder = async params => {
  const defaultOrder = {
    related_no: null,
    coupon_price: 0,
    freight_price: 0,
    discount: 1,
    status: 1,
    pay_status: 0,
    is_delete: 0
  }
  const {
    store_id,
    store_no,
    customer_id,
    customer_name,
    company_name,
    order_type,
    coupon_price = 0,
    freight_price = 0,
    total_num,
    total_price,
    discount = 1,
    status = 1,
    pay_status = 0,
    pay_time = null,
    is_delete = 0,
    remarks,
    goods_list
  } = params

  const orderRes = await getOrderList({ store_id, create_time: [moment(new Date()).format("YYYY-MM-DD 00:00:00")] });
  console.log("createOrder--orderRes: %s--%s==", JSON.stringify(orderRes), orderRes.length)
  const order_no = handleOrderNo(store_no, orderRes.length+1);
  console.log('createOrder--order_no: %s==', order_no)
  // create_time, update_time)
  // const sql = `INSERT INTO sp_store_order (store_id, order_id, order_no, customer_id, customer_name, company_name, order_type, coupon_price, freight_price, total_price, discount, total_num, status, pay_status, pay_time, is_delete, remarks) VALUES (${store_id}, ${order_id}, (select CONCAT(date_format(now(),'%Y%m%d'), ${store_no}, LPAD((COUNT(*)+1)+'',3,'0')) as order_no from sp_store_order o where o.order_no like CONCAT(CONCAT( date_format(now(),'%Y%m%d'), ${store_no} ),'%')),${customer_id}, ${customer_name}, '${company_name}', ${order_type}, ${coupon_price}, ${freight_price}, ${total_price}, ${discount}, ${total_num}, ${status}, ${pay_status}, ${pay_time}, ${is_delete}, '${remarks}')`
  // console.log("createOrder--goods_list: %s==", JSON.stringify(goods_list))
  let result = null;
  // const payload = { ...defaultOrder, ...params, order_id, order_no: order_id, goods_list: [] }
  const payload = Object.assign({}, defaultOrder, params, { order_no });
  console.log("createOrder--payload: %s==", JSON.stringify(payload))
  try {
    result = await Order.create({ ...payload, goods_list });
    console.log("createOrder--result: %s==", JSON.stringify(result))
    let orderGoodsRes = await createOrderGoods(payload, result.id)
    // console.log("createOrder--orderGoodsRes: %s==", JSON.stringify(orderGoodsRes))
    // let stockRes = await GoodsController.updataStock(result.id);
    // console.log("createOrder--stockRes: %s==", JSON.stringify(stockRes))
  } catch (err) {
    console.log("createOrder--err: %s==", JSON.stringify(err));
    return err;
  }
  
  // sqlConn(sql, [], (err, res) => {
  //   console.log("createOrder--sqlConn--err:%s==", JSON.stringify(err))
  //   console.log("createOrder--sqlConn--res:%s==", JSON.stringify(res))
  //   if (err) {
  //     result = err
  //   } else {
  //     result = { code: 200, data: res.insertId }
  //     // 写入订单商品数据
  //     bulkCreateOrderGoods(goods_list, res.insertId, store_no)
  //   }
  //   return result
  // })
  return result
}
// 生成订单号
const handleOrderNo = (store_no, baseStr = 1) => {
  const fullNum = Math.ceil(baseStr / 10);
  let orderNum = '';
  for (let i = 0; i < 4 - fullNum; i++) {
    orderNum = orderNum + '0';
  }
  orderNum = orderNum + baseStr;
  const curDate = moment(new Date()).format("YYYYMMDD");
  const orderNo = curDate + store_no + orderNum;
  // const orderNo = `${curDate}${store_no}${orderNum}`;
  console.log('handleOrderNo--store_no: %s--baseStr: %s--%s--', store_no, baseStr, orderNo)

  return orderNo;
}
const handleOrderNo2 = (store_no, baseStr = 1) => {
  const orderNum = baseStr.padStart(4, '0');
  const curDate = moment(new Date()).format("YYYY-MM-DD");
  const orderNo = `${curDate} + ${store_no} + ${orderNum}`;
  console.log('handleOrderNo--store_no: %s--baseStr: %s--%s--', store_no, baseStr, orderNo)

  return orderNo;
}

// 插入订单商品信息
const createOrderGoods = async (params, order_id) => {
  const {
    order_type,
    goods_list,
  } = params;
  const goodsList = goods_list.map(d => {
    return { ...d, order_id, order_type }
  });
  console.log("createOrderGoods--goods_list: %s==", JSON.stringify(goods_list))
  try {
    result = await OrderGoods.bulkCreate(goodsList);
    console.log("createOrderGoods--result: %s==", JSON.stringify(result))
  } catch (err) {
    console.log("createOrderGoods--err: %s==", JSON.stringify(err));
    return err;
  }

}

// 更新订单信息
const updataOrder = async params => {

}

// 更新商品库存信息
const updataGoodValue = async params => {
  const { 
    order_id,
    goods_list
  } = params;
  let 

}

// 写入订单商品数据
const bulkCreateOrderGoods = async (goods_list, order_id, store_no) => {
  try {
    const params = goods_list.map(d => {
      d.order_id = order_id
      d.order_no = ""
      return d
    })
    // console.log("bulkCreateOrderGoods--params:%s==", JSON.stringify(params))
    const result = await OrderGoods.bulkCreate(params)
    // console.log("bulkCreateOrderGoods--result:%s==", JSON.stringify(result))
    return result
  } catch (e) {
    console.log("bulkCreateOrderGoods--e== %s==", e)
    return null
  }
}
// 获取订单列表
const getOrderList = async params => {
  // const sql = `select * from sp_store_order where store_id = ${params.store_id}`;
  let sql = `select * from sp_store_order`;
  let paramStr = '';
  if (params) {
    Object.keys(params).forEach((d, i) => {
      if (i !== 0) {
        paramStr += ' and '
      }
      if (d === 'store_id') { // 店铺
        paramStr += 'store_id in (' + params[d] + ')';
      }
      if (d === 'status') { // 订单状态
        paramStr += 'status in (' + params[d] + ')';
      }
      if (d === 'create_time') { // 创建时间
        if (Array.isArray(params[d]) && params[d].length) {
          if (params[d].length === 1) {
            paramStr += `create_time >= '${params[d][0]}'` ;
          }
          else {
            paramStr += `create_time >= '${params[d][0]}' and create_time <= '${params[d][1]}'` ;
          }
        }
        else {
          paramStr += 'create_time >= ' + params[d];
        }
      }
      if (d === 'end_time') { // 创建时间
        paramStr += 'create_time >= ' + params[d];
      }
    })
  }
  console.log('getOrderList--paramStr: %s==', paramStr);
  if (paramStr) {
    sql = sql + ' where ' + paramStr;
  }
  console.log('getOrderList--sql: %s==', sql);
  let result = null
  return new Promise((resolve,reject) => {
    sqlConn(sql, [], (err, res) => {
      console.log("createOrder-getOrderList-sqlConn--err: %s==", JSON.stringify(err))
      console.log("createOrder-getOrderList-sqlConn--res: %s==", JSON.stringify(res))
      if (err) {
        result = err
      } else {
        result = res
      }
      resolve(result)
    })
  })
}
// 订单详情
const orderDetail = async params => {
  const { id } = params
  const data = await Order.findOne({
    where: { id },
    include: [
      {
        association: OrdersHasManyGoods
      }
    ]
  })
  console.log("orderDetail--%s==", JSON.stringify(data))
  return { data }
}

const getOrderDetail = async params => {
  const { id } = params
  console.log("getOrderDetail--id:s%==", id)
  const result = await orderDetail(params)
  console.log("getOrderDetail--%s==", JSON.stringify(result))
  return result.data
}

// 更新订单状态
// 1:待发货，3:已发货，4:已完成，5:已取消，6:已支付
const updataStatus = async params => {
  const { id, status, store_id } = params
  try {
    // 获取订单数据
    const { data: order } = await orderDetail({ id })
    // 更新订单操作
    console.log(
      "order_controller/updataStatus-result-%s=",
      JSON.stringify(order)
    )
    let isUpdate = false
    // 当订单为待发货 且更新状态不为取消时，需更新商品库存信息
    // status 订单状态：1:未发货 2:已发货 3: 已收货 4: 已退货 5: 已完成 6: 已评价 7: 已取消 8: 已删除
    // order_type 订单类型：1: 采购入库，2: 销售出库，3: 同价调拨， 4: 其他入库，5: 采购退货，6: 报溢单，7: 报损单，8: 其他出库
    if (order.status === "1" && ["2", "3", "4", "6"].includes(status)) { // 
      // 获取用户信息
      const customer = await Customer.findOne({
        where: { id: order.customer_id }
      })
      // const customerConfig = JSON.parse(customer.config || "{}")
      // const isAllowLoad = customerConfig.isAllowLoad || false
      // const stockRes = await GoodsController.updateStock({
      //   goods_list: order.goods_list,
      //   isAllowLoad,
      //   operation: "reduce"
      // })

      // const res = await CustomerController.updateCustomerConfig({
      //   order,
      //   customer
      // })
      // console.log(
      //   "updataStatus--updateCustomerConfig--res: %s==",
      //   JSON.stringify(res)
      // )

      let stockRes = await GoodsController.updataStock(id);
      console.log("updataStatus-stockRes-%s=", JSON.stringify(stockRes));
    }
    else if (["2", "3", "4", "6"].includes(order.status) && status === "1") {  // 订单状态改为待发货，商品库存恢复
      // const stockRes = await GoodsController.updateStock({
      //   goods_list: order.goods_list,
      //   isAllowLoad: false,
      //   operation: "add"
      // })
      // console.log("恢复库存-:updataStatus--stockRes: %s==", JSON.stringify(stockRes))
    }
    let result;
    // result = await Order.update({ status }, { where: { id } })
    
    return result
  } catch (err) {
    console.log("order_controller/updataStatus--err:%s==", err)
  }
}

module.exports = {
  getOrderList,
  createOrder,
  getOrderDetail,
  updataStatus
}
